texture ColorRT;
texture NormalRT;
texture DepthRT;
float2 halfPixel;

float4x4 InvertViewProjection; 

float3 cameraPosition;
float3 diffuseColor;
float3 lightIntensity;
float3 lightDirection;

sampler colorSampler = sampler_state
{
    Texture = (ColorRT);
    AddressU = CLAMP;
    AddressV = CLAMP;
    MagFilter = LINEAR;
    MinFilter = LINEAR;
    Mipfilter = LINEAR;
};

sampler normalSampler = sampler_state
{
    Texture = (NormalRT);
    AddressU = CLAMP;
    AddressV = CLAMP;
    MagFilter = LINEAR;
    MinFilter = LINEAR;
    Mipfilter = LINEAR;
};

sampler depthSampler = sampler_state
{
    Texture = (DepthRT);
    AddressU = CLAMP;
    AddressV = CLAMP;
    MagFilter = LINEAR;
    MinFilter = LINEAR;
    Mipfilter = LINEAR;
};

struct VertexShaderInput
{
    float3 Position : POSITION0;
    float2 TexCoord : TEXCOORD0;
};

struct VertexShaderOutput
{
	float4 Position : POSITION0;
	float2 TexCoord : TEXCOORD0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    output.Position = float4(input.Position,1);
    output.TexCoord = input.TexCoord - halfPixel;

    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float4 normalData = tex2D(normalSampler,input.TexCoord);
    
    float3 normal = 2.0f * normalData.xyz - 1.0f;
    normal = normalize(normal);
    
    float specularPower = normalData.a * 255;
    
    float specularIntensity = tex2D(colorSampler, input.TexCoord).a;
    
    float depthVal = tex2D(depthSampler,input.TexCoord).r;
    
    float4 position;
    position.x = input.TexCoord.x * 2.0f - 1.0f;
    position.y = -(input.TexCoord.y * 2.0f - 1.0f);
    position.z = depthVal;
    position.w = 1.0f;
    
    position = mul(position, InvertViewProjection);
    position /= position.w;
    
    float3 lightVector = -normalize(lightDirection);
    
    float NdL = max(0,dot(normal,lightVector));
    float3 diffuseLight = NdL * diffuseColor.rgb;
    
    float3 reflectionVector = normalize(reflect(lightVector, normal));
    float3 directionToCamera = normalize(cameraPosition - position);
    
    float specularLight = specularIntensity * pow( saturate(dot(reflectionVector, directionToCamera)), specularPower);

    return float4(diffuseLight.rgb * lightIntensity, specularLight)  * tex2D(colorSampler, input.TexCoord);
}

technique Technique1
{
    pass Pass1
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}